<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>刻意练</h2>
        <p>管理员登录</p>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            size="large"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="verifyCode">
          <el-input
            v-model="loginForm.verifyCode"
            placeholder="请输入图形验证码"
            size="large"
            :prefix-icon="Lock"
            @focus="handleVerifyFocus"
          >
            <template #append>
              <img v-if="captchaImage" :src="captchaImage" alt="Captcha" class="captcha-img" @click="getCaptcha" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getVerifyCode } from '@/api/user'


const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref()
const loading = ref(false)

const captchaImage = ref('')

const loginForm = reactive({
  phone: '',
  verifyCode: ''
})

const loginRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  verifyCode: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
  ]
}

const getCaptcha = () => {
  const phone = (loginForm.phone || '').trim()

  getVerifyCode({ phone })
    .then(res => {
      captchaImage.value = res
    })
    .catch(err => {
      captchaImage.value = ''
      console.error('获取图形验证码失败', err)
    })
}

const handleVerifyFocus = () => {
  getCaptcha()
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    await userStore.webLogin(loginForm)
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
    getCaptcha()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getCaptcha()
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-box {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.login-header {
  text-align: center;
  margin-bottom: 30px;
}
.login-header h2 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}
.login-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}
.login-form {
  margin-top: 20px;
}
.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
}
.el-input {
  margin-bottom: 10px;
}
.captcha-img {
  width: 100px;
  height: 38px;
  cursor: pointer;
  /* 修正el-input-group__append的内边距，使图片填满 */
  margin: -10px -20px;
}
</style>